<template>
    <div class="app-container">
        <el-row class="row-padding">
            <el-form :inline="true">
                <el-form-item :label="$t('dataList.sample')">
                  <el-input v-model="sample" style="width: 180px"></el-input>
                </el-form-item>
                <el-form-item :label="$t('dataList.username')">
                  <el-input v-model="userName"  style="width: 180px"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button class="el-button--primary el-button--small"  icon="el-icon-search" @click="query"></el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-table
                :data="tableData"
                :current-page.sync="currentPage"
                element-loading-text="Loading"
                max-height="800"
                highlight-current-row
        >
            <el-table-column :label="$t('dataList.label')">
                <template slot-scope="scope">
                    {{ scope.row.id }}
                </template>
            </el-table-column>
            <el-table-column :label="$t('dataList.sample')" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.sample }}</span>
                </template>
            </el-table-column>
            <el-table-column :label="$t('dataList.result')" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.receiving.niandu }}</span>
                </template>
            </el-table-column>
            <el-table-column :label="$t('dataList.createTime')" align="center" :formatter="timeFormater"  width="115">
            </el-table-column>
            <el-table-column :label="$t('dataList.username')" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.username }}</span>
                </template>
            </el-table-column>
            <el-table-column
                    fixed="right"
                    :label="$t('dataList.action')"
                    width="115"
            >
                <template  slot-scope="{row}"  style="width: 200px">
                    <el-button type="text" size="small" icon="el-icon-printer" @click="handlePrint(row)"></el-button>
                    <el-button type="text" size="small" icon="el-icon-view" @click="handleShowDetail(row)"></el-button>
                    <el-button type="text" size="small" icon="el-icon-delete" @click="handleDelete(row)"></el-button>

                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :page-sizes="[10, 15, 20, 50]"
                    :page-size="pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <el-dialog
                :visible.sync="dataListDetailDialogVisible"
                width="80%"
                center
                >
            <div id="printArea">

                <el-row :gutter="12">
                    <el-col :span="24" style="color: white; margin-bottom: 10px">
                      <el-card>
                          <div style="text-align: center; font-size: 20px; margin-top: 20px ">{{measureData.setting.sampleName}}&nbsp;&nbsp;{{$t("print.title")}}</div>
                          <div style="font-size: 14px ; text-align: right; line-height: 30px; margin-right: 20px">
                            <div >{{$t("print.time")}}&nbsp;&nbsp;{{printMeasureTime}}</div>
                          </div>
                      </el-card>
                    </el-col>
                    <el-col :span="24">
                        <el-card shadow="always">
                            <div slot="header" class="clearfix">
                                <span> {{$t("lab.setting")}}</span>
                            </div>
                            <div>
                                <el-form ref="setting" label-width="auto">
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.sampleName')">
                                            {{measureData.setting.sampleName}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.model')">
                                            {{measureData.setting.model}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.timeGap')">
                                            {{measureData.setting.timeGap}}s
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.measureTime')">
                                            {{measureData.setting.measureTime}}m
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.spindle')">
                                            {{measureData.setting.spindle | spindleFormatter}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.rpm')" >
                                            {{measureData.setting.rpm}} RPM
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.operator')">
                                            {{measureData.setting.operator}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                      <el-form-item :label="$t('lab.density')">
                                        {{measureData.setting.density}}
                                      </el-form-item>
                                    </el-col>

                                </el-form>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-card shadow="always">
                            <div slot="header" class="clearfix"/>
                            <div slot="header" class="clearfix">
                                <span> {{$t("lab.receiving")}}</span>
                            </div>
                            <div>
                                <el-form ref="form" label-width="auto">
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.naindu')" >
                                            {{measureData.receiving.niandu}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                      <el-form-item :label="$t('lab.yunDongNianDu')" >
                                        {{measureData.receiving.yunDongNianDu}}
                                      </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.temperture')" >
                                            {{measureData.receiving.temperture}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.spindle')">
                                            {{measureData.receiving.spindle  | spindleFormatter}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.rpm')">
                                            {{measureData.receiving.rpm}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.ratio')">
                                            {{measureData.receiving.ratio}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.ss')">
                                            {{measureData.receiving.ss}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item :label="$t('lab.sr')">
                                            {{measureData.receiving.sr}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :md="12"  :xs="24" v-if="showSuperAdmin">
                                        <el-form-item :label="$t('lab.m1')">
                                            {{measureData.receiving.m1}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :md="12"  :xs="24" v-if="showSuperAdmin">
                                        <el-form-item :label="$t('lab.m2')">
                                            {{measureData.receiving.m2}}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12" v-if="showSuperAdmin">
                                        <el-form-item :label="$t('lab.m3')">
                                            {{measureData.receiving.m3}}
                                        </el-form-item>
                                    </el-col>

                                </el-form>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-card shadow="always">
                            <div slot="header" class="clearfix">
                                <span> {{$t("lab.pic")}}</span>
                            </div>
                            <div>
                                <highcharts :options="chartOptions" ref="chart"></highcharts>
                            </div>
                           <el-row class="row-padding printHide" >
                                <el-button type="primary" @click="exportExcel">{{$t('chart.downLoad')}}</el-button>
                                <el-button type="success" @click="screenShot">{{$t('lab.exportResult')}}</el-button>
                            </el-row>

                            <div class="printHide">
                                <el-table
                                        :data="detailTableData.slice((currentPageDetail-1)*pageSizeDetail,currentPageDetail*pageSizeDetail)"
                                        stripe
                                        border
                                        style="width: 100%; margin-top: 10px"
                                        id="out-table"
                                >
                                    <el-table-column :label="$t('chart.xAxis')" :formatter="timeFormatter">
                                    </el-table-column>
                                    <el-table-column :label="$t('chart.serialName1')" align="center">
                                        <template slot-scope="scope">
                                            <span>{{ scope.row.niandu }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column :label="$t('chart.serialName2')" align="center">
                                        <template slot-scope="scope">
                                            {{ scope.row.temperture }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column :label="$t('chart.serialName3')" align="center" >
                                        <template slot-scope="scope">
                                            {{ scope.row.ratio }}
                                        </template>
                                    </el-table-column>
                                </el-table>
                                <el-pagination align='center'
                                               @size-change="handleSizeChangeDetail"
                                               @current-change="handleCurrentChangeDetail"
                                               :current-page="currentPageDetail"
                                               :page-sizes="[10,20,50]"
                                               :page-size="pageSizeDetail"
                                               layout="total, sizes, prev, pager, next, jumper"
                                               :total="detailTableData.length">
                                </el-pagination>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </el-dialog>
        <el-dialog
                :title="$t('print.view')"
                :visible.sync="printDialogShow"
                width="80%"
                :before-close="handleClose"
        >
            <DataPrintPanel :dataList="printDataList" :operator="printOperator" :dateTime="printMeasureTime" :header="printHeader" v-on:close="closePrintDialog"></DataPrintPanel>
        </el-dialog>
    </div>
</template>

<style lang="scss">
    .app-container {

        .row-padding {
            margin-bottom: 20px;
            margin-top: 20px;
        }

        .el-form-item__label {
          color: white !important;
          font-size: 18px
        }

    }

</style>

<script>
    import { queryMeasureDataList, countMeasureData, deleteMeasureData } from '../../../api/measuredata'
    import dayjs from 'dayjs'
    import {formatMMSS, spindleFormatter} from "../../../utils/util";
    import * as XLSX from "xlsx";
    import FileSaver from "file-saver";
    // import printJS from 'print-js'
    import html2canvas from 'html2canvas'
    import JsPDF from 'jspdf'


    export default {
        data() {
            return {
                sample: "",
                userName:"",
                tableData: [],
                listLoading: true,
                currentPage: 1,
                pagesize: 10,
                total: 0,
                modifyCenterDialogVisible: false,
                measureData: {
                    "setting":{},
                    "receiving":{}
                },
                chartOptions: {
                    zoomType: 'x',
                    title: {
                        text: this.$i18n.tc("chart.title")
                    },
                    yAxis: {
                        title: {
                            text: this.$i18n.tc("chart.yAxis")
                        }
                    },
                    xAxis: {
                        title: {
                            text: this.$i18n.tc("chart.xAxis")
                        },
                        labels:{
                            formatter : function(){
                                return formatMMSS(this.value);
                            }
                        }
                    },
                    credits:{
                        enabled: false
                    },
                    tooltip: {
                        shared: true,
                        useHTML: true,
                        headerFormat:"",
                        pointFormatter: function () {
                            return formatMMSS(this.x) +  '<br/><span style="color: '+ this.series.color + '">\u25CF</span> '+
                                this.series.name+   ': <b>'+ this.y +'</b><br/>'
                        },
                    },
                    series: [],
                    responsive: {
                        rules: [
                            {
                                condition: {
                                    maxWidth: 500
                                },
                                credits:{
                                    enabled: false // 禁用版权信息
                                }
                            }
                        ]
                    },
                    exporting: {
                      buttons: {
                        contextButton: {
                          menuItems: ['viewFullscreen']
                        }
                      }
                    }
                },
                dataListDetailDialogVisible: false,
                printDialogShow: false,
                printDataList:[],
                printMeasureTime:"",
                printOperator:"",
                printHeader:"",
                detailTableData:[],
                currentPageDetail: 1,
                totalDetail: 0,
                pageSizeDetail: 10
            }
        },
        filters:{
            spindleFormatter(value) {
                return spindleFormatter(value)
            }
        },
        created() {
            this.fetchData()
        },
        computed:{
            showSuperAdmin() {
                console.info("roles is " + this.$store.state.user.roles);
                return this.$store.state.user.roles == "SUPPERADMIN";
            }
        },
        methods: {
            async fetchData() {
                this.listLoading = true;
                let condition = {sample: this.sample, username: this.userName, start: (this.currentPage - 1) * this.pagesize, size: this.pagesize};
                if (this.$store.state.user.roles.indexOf("SUPPERADMIN") === -1 && this.$store.state.user.roles.indexOf("ADMIN") === -1) {
                    condition["createOn"] = this.$store.state.user.id;
                }
                this.total = await countMeasureData(condition);
                queryMeasureDataList(condition).then(dataList => {
                    this.tableData = dataList;
                    this.listLoading = false
                })
            },
            handleSizeChange(val) {
                this.pagesize = val;
                this.fetchData()
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.fetchData();
            },
            query(){
                this.fetchData();
            },
            timeFormater(row) {
               return dayjs(row.createTime).format('YYYY-MM-DD HH:mm')
            },
            handleDelete(data) {
                this.$confirm(this.$i18n.tc("dataList.deleteTip") + ": " + data.sample, {type: 'warning'}).then(() => {
                    deleteMeasureData(data.id);
                    this.fetchData();
                    this.$message({
                        type: 'success',
                        message: this.$i18n.tc("dataList.deleteSuccessTip")
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: this.$i18n.tc("dataList.deleteCancelTip")
                    })
                })
            },
            handleShowDetail(data) {
                this.measureData = data;
                this.chartOptions.series = data.data;
                this.dataListDetailDialogVisible = true;
                this.printMeasureTime = dayjs(data.createTime).format('YYYY-MM-DD HH:mm');

                let index1 = 0;
                let index2 = 0;
                let index3 = 0;
                while (index1 < this.chartOptions.series[0].data.length || index2 < this.chartOptions.series[1].data.length || index3 < this.chartOptions.series[2].data.length) {
                    let curData1 = 999999999;
                    let curData2 = 999999999;
                    let curData3 = 999999999;
                    if (index1 < this.chartOptions.series[0].data.length) {
                        curData1 = this.chartOptions.series[0].data[index1][0]
                    }
                    if (index2 < this.chartOptions.series[1].data.length) {
                        curData2 = this.chartOptions.series[1].data[index2][0];
                    }
                    if (index3 < this.chartOptions.series[2].data.length) {
                        curData3 = this.chartOptions.series[2].data[index3][0];
                    }
                    let curTime = Math.min(curData1, curData2, curData3);
                    let tableItem = {};
                    tableItem["time"] = curTime;
                    if (curTime === curData1) {
                        tableItem["niandu"] = this.chartOptions.series[0].data[index1][1];
                        index1++;
                    }
                    if (curTime === curData2) {
                        tableItem["temperture"] = this.chartOptions.series[1].data[index2][1];
                        index2++;
                    }
                    if (curTime === curData3) {
                        tableItem["ratio"] = this.chartOptions.series[2].data[index3][1];
                        index3++;
                    }
                    this.detailTableData.push(tableItem)
                }
            },
            closePrintDialog(){
                this.printDialogShow = false;
            },
            handleClose(done) {
                this.$confirm(this.$i18n.tc("print.closeConfirm"))
                    .then( () => {
                        done();
                    })
                    .catch( ()=> {});
            },
            handleSizeChangeDetail(val) {
                console.log(`每页 ${val} 条`);
                this.currentPageDetail = 1;
                this.pageSizeDetail = val;
            },
            //当前页改变时触发 跳转其他页
            handleCurrentChangeDetail(val) {
                console.log(`当前页: ${val}`);
                this.currentPageDetail = val;
            },
            timeFormatter(row) {
                return formatMMSS(row.time);
            },
            handlePrint(row){
                this.printDialogShow = true;
                this.printHeader = row.setting.sampleName;
                this.printOperator = row.setting.operator;
                this.printMeasureTime = dayjs(row.createTime).format('YYYY-MM-DD HH:mm');

                this.printDataList = [
                    {
                        "label" :  this.$i18n.tc("lab.sampleName"),
                        "value": row.setting.sampleName
                    },
                    {
                        "label" :  this.$i18n.tc("lab.model"),
                        "value": row.setting.model
                    },
                    {
                        "label" :  this.$i18n.tc("lab.timeGap"),
                        "value": row.setting.timeGap + " s"
                    },
                    {
                        "label" :  this.$i18n.tc("lab.measureTime"),
                        "value": row.setting.measureTime + " m"
                    },
                    {
                        "label" :  this.$i18n.tc("lab.spindle"),
                        "value":  spindleFormatter(row.setting.spindle)
                    },
                    {
                        "label" :  this.$i18n.tc("lab.rpm"),
                        "value": row.setting.rpm
                    },
                    {
                        "label" :  this.$i18n.tc("lab.naindu"),
                        "value": row.receiving.niandu
                    },
                    {
                      "label" :  this.$i18n.tc("lab.yunDongNianDu"),
                      "value": row.receiving.yunDongNianDu
                    },
                    {
                        "label" :  this.$i18n.tc("lab.ratio"),
                        "value": row.receiving.ratio
                    },
                    {
                        "label" :  this.$i18n.tc("lab.ss"),
                        "value": row.receiving.ss
                    },
                    {
                        "label" :  this.$i18n.tc("lab.sr"),
                        "value": row.receiving.sr
                    }
                ]
            },
            async exportExcel() {
                let pageSize = this.pageSizeDetail;
                this.pageSizeDetail = this.detailTableData.length;
                this.$nextTick(function () {
                    let ws1 = XLSX.utils.table_to_book(document.querySelector('#out-table'));//对应要导出的表格id
                    /* get binary string as output */
                    let wbOut = XLSX.write(ws1, {
                        bookType: "xlsx",
                        bookSST: true,
                        type: "array"
                    });
                    try {
                        FileSaver.saveAs(
                            new Blob([wbOut], { type: "application/octet-stream"}),
                            "Viscometer-" + dayjs().format("YYYYMMDDHHmms") + ".xlsx"
                        );
                    } catch (e) {
                        if (typeof console !== "undefined") console.log(e, wbOut);
                    }
                    this.pageSizeDetail = pageSize; //表格还原
                    return wbOut;
                });

            },
            screenShot() {
                console.log("devicePixelRatio is : " + window.devicePixelRatio);

                const el = document.querySelector('#printArea');

                html2canvas(el,
                    {
                        // dpi: 500,
                        scale:2,
                        background: "#fff",
                        allowTaint: true,
                        height : el.outerHeight,
                        ignoreElements:(element)=>{
                            let flag = false;
                            element.classList.forEach(item => {
                                flag = flag || item === 'printHide'}
                            );
                            return flag;
                        }
                    }).then((canvas)=> {
                    let contentWidth = canvas.width;
                    let contentHeight = canvas.height;
                    console.log("contentWidth " + contentWidth);
                    console.log("contentHeight " + contentHeight);

                    if (contentHeight < contentWidth) {
                        // 等比例图片放大
                        //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
                        let imgWidth = 841.89;
                        // let
                        let imgHeight = 841.89 / contentWidth * contentHeight;

                        if (imgHeight >  595.28 && imgHeight <=  595.28 * 1.1) {
                            console.log("imgHeight 1.1区间诶");
                            imgHeight = 595.28;
                        } else if (imgHeight > 595.28 * 1.1) {
                            console.log("imgHeight 过大");
                            imgHeight = 595.28;
                            imgWidth = 595.28 *  contentWidth / contentHeight;
                        } else {
                            console.log("imgHeight非1.1区间")
                        }
                        console.log("imgHeight " + imgHeight);
                        console.log("imgWidth " + imgWidth);


                        let pageData = canvas.toDataURL('image/jpeg', 1.0);
                        let pdf = new JsPDF('l', 'pt', 'a4');

                        pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);

                        pdf.save(dayjs().format("YYYYMMDDHHmmsss") + '.pdf');

                        //document.body.appendChild(canvas)  页面布局会乱
                        //转换base64
                        // const capture = canvas.toDataURL('image/png');
                        // printJS({
                        //     printable: pdf.output('bloburl'),
                        //     type: 'pdf',
                        //     style: "@page {size:landscape; margin: 0;}"
                        // });
                    } else {

                        //一页pdf显示html页面生成的canvas高度;
                        let pageHeight = contentWidth / 595.28 * 841.89;
                        console.log("pageHeight " + pageHeight);

                        //未生成pdf的html页面高度
                        let leftHeight = contentHeight;
                        console.log("leftHeight " + leftHeight);

                        //页面偏移
                        let position = 0;
                        //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
                        let imgWidth = 595.28;
                        let imgHeight = 595.28 / contentWidth * contentHeight;


                        console.log("imgHeight " + imgHeight);
                        console.log("imgWidth " + imgWidth);

                        let pageData = canvas.toDataURL('image/jpeg', 1.0);

                        let pdf = new JsPDF('', 'pt', 'a4');

                        //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
                        //当内容未超过pdf一页显示的范围，无需分页
                        if (leftHeight < pageHeight) {
                            pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
                        } else {
                            console.log("多页显示");
                            while(leftHeight > 0) {
                                console.log("position " + position);
                                pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
                                leftHeight -= pageHeight;
                                console.log("leftHeight" + leftHeight);
                                position -= 841.89;
                                console.log("position" + position);

                                //避免添加空白页
                                if(leftHeight > 0) {
                                    pdf.addPage();
                                }
                            }
                        }
                        pdf.save(dayjs().format("YYYYMMDDHHmmsss") + '.pdf');

                        //document.body.appendChild(canvas)  页面布局会乱
                        //转换base64
                        // const capture = canvas.toDataURL('image/png');
                        // printJS({
                        //     printable:  pdf.output('bloburi'),
                        //     type: 'pdf',
                        //     style: "@page {size:landscape; margin: 0;}"
                        // });
                    }

                })
            },

        }
    }
</script>
